<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addDialogVisible = true">
                        添加角色
                    </el-button>
                </el-col>
            </el-row>
            <el-table :data="rolelist" border stripe>
                <el-table-column width="45px" type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
                            v-for="(item1, i1) in scope.row.children" :key="item1.id">
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row.id, item1.id)">{{ item1.authName
                                }}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col :span="19">
                                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children"
                                    :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row.id, item2.id)">
                                            {{ item2.authName }}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag v-for="(item3, i3) in item2.children" :key="item3.id" type="warning"
                                            closable @close="removeRightById(scope.row.id, item3.id)">
                                            {{ item3.authName }}
                                        </el-tag>
                                    </el-col>

                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-row>
                            <el-button type="primary" size="mini" icon="el-icon-edit"
                                @click="showEditDialog(scope.row.id)">编辑</el-button>
                            <el-button type="danger" size="mini" icon="el-icon-delete"
                                @click="removeById(scope.row.id)">删除</el-button>
                            <el-button type="warning" size="mini" icon="el-icon-setting"
                                @click="showSetRightDialog(scope.row)">分配权限</el-button>
                        </el-row>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加角色 -->
        <el-dialog title="添加角色" :visible.sync="addDialogVisible" @close="addDislogClosed">
            <el-form :model="addRolesForm" :rules="addFormRules" ref="addRolesForm" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRolesForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRolesForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRolesUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改角色信息 -->
        <el-dialog title="修改角色信息" :visible.sync="editDialogVisible">
            <el-form :model="editRolesForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRolesForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRolesForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editFormInfo">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限对话框 -->
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
            <el-tree :data="rightslist" :props="treeProps" show-checkbox node-key="id" default-expand-all="true"
                :default-checked-keys="defKeys" ref="treeRef"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import Rights from './Rights.vue'

export default {

    data() {
        return {
            //所有角色列表数据
            rolelist: [],
            addDialogVisible: false,
            editDialogVisible: false,
            addRolesForm: {
                roleName: '',
                roleDesc: ''
            },
            addFormRules: {},
            editRolesForm: {},
            editFormRules: {},
            setRightDialogVisible: false,
            rightslist: [],
            treeProps: {
                label: 'authName',
                children: 'children'
            },
            defKeys: [

            ],
            roleId:''
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
        async getRolesList() {
            const { data: res } = await this.$http.get("roles")
            if (res.meta.status !== 200) {
                this.$message.error("获取用户角色列表失败！")
            }
            this.rolelist = res.data
            console.log(this.rolelist)
        },
        addRolesUser() {
            this.$refs.addRolesForm.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.post('roles', this.addRolesForm)
                console.log(res)
                if (res.meta.status !== 201) {
                    return this.$message.error('添加角色失败!')
                }
                this.$message.success('添加角色成功!')
                this.getRolesList()
                this.addDialogVisible = false
            })
            // console.log(this.addRolesForm)
        },
        // 清空添加角色对话框
        addDislogClosed() {
            this.$refs.addRolesForm.resetFields()
        },
        async showEditDialog(id) {
            const { data: res } = await this.$http.get('roles/' + id)
            if (res.meta.status !== 200) {
                return this.$message.error("修改角色信息失败！")
            }
            this.editRolesForm = res.data
            this.editDialogVisible = true
        },
        // editDialogClosed() {
        //     this.$refs.editFormRef.resetFields()
        // },
        editFormInfo() {
            this.$refs.editFormRef.validate(async valid => {
                if (!valid) { return }
                const { data: res } = await this.$http.put('roles/' + this.editRolesForm.roleId, {
                    roleName: this.editRolesForm.roleName,
                    roleDesc: this.editRolesForm.roleDesc
                })
                console.log(res)
                if (res.meta.status !== 200) {
                    this.$message.error("修改提交角色信息失败！")
                } else {
                    this.$message.success("修改提交角色信息成功！")
                    this.getRolesList();
                }
                this.editDialogVisible = false

            })
        },
        async removeById(id) {
            console.log(id)
            const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '删除用户', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(error => error)
            console.log(confirmResult)
            if (confirmResult !== "confirm") {
                return this.$message.info("已取消删除")
            }
            const { data: res } = await this.$http.delete('roles/' + id)
            console.log(res)
            if (res.meta.status !== 200) {
                return this.$message.error("删除角色失败！")
            } else {
                this.$message.success("删除角色成功！")
                this.getRolesList()
            }

        },
        async removeRightById(roles, id) {
            const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '删除用户', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(error => error)
            console.log(confirmResult)
            if (confirmResult !== "confirm") {
                return this.$message.info("已取消删除")
            }
            const { data: res } = await this.$http.delete(
                `roles/${roles.id}/rights/${id}`
            );
            console.log(res)
            if (res.meta.status !== 200) {
                return this.$message.error("删除角色权限失败！")
            } else {
                this.$message.success("删除角色权限成功！")
                // this.getRolesList();
                roles.children = res.data;

            }
        },
        async showSetRightDialog(role) {
            this.roleId = role.id
            const { data: res } = await this.$http.get("rights/tree")
            console.log(res)
            if (res.meta.status !== 200) {
                return this.$message.error("获取权限数据失败！")
            }
            this.rightslist = res.data
            //递归获取三级节点的id
            this.getLeafKeys(role, this.defKeys)
            console.log(this.rightslist)
            this.setRightDialogVisible = true
        },
        getLeafKeys(node, arr) {
            //如果没有孩子节点的话，那就是三级目录，读取到这个并将这个放在arr数组中
            if (!node.children) {
                return arr.push(node.id)
            }
            console.log(node)

            // 有孩子的节点的话，那就是需要遍历这个节点下面的
            node.children.forEach(item =>
                this.getLeafKeys(item, arr)
            );
        },
        setRightDialogClosed() {
            this.defKeys = []
        },
       async allotRights() {
            const keys = [
                ... this.$refs.treeRef.getCheckedKeys(),

                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            // console.log(keys)
            const idStr = keys.join(',')
          const {data : res} = await this.$http.post(`roles/${this.roleId}/rights`,
            {rids:idStr} 
            )
            if(res.meta.status !==200){
                return this.$message.error("对应角色下分配权限失败！")
            }
            this.$message.success("对应角色下分配权限成功！")
            this.getRolesList()
            this.setRightDialogVisible = false
        }
    }

}

</script>2
<style scoped>
.el-tag {
    margin: 7px;
}

.bdtop {
    border-top: 1px solid black;
}

.bdbottom {
    border-bottom: 1px solid black;
}

.vcenter {
    display: flex;
    align-items: center;
}
</style>